package com.cuoyi.coupon.mall.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.cuoyi.coupon.mall.common.ApiResult;
import com.cuoyi.coupon.mall.config.SessionLocal;
import com.cuoyi.coupon.mall.constant.BusinessConstant;
import com.cuoyi.coupon.mall.model.dto.UserDTO;
import com.cuoyi.coupon.mall.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.CharEncoding;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author chengzhang
 * 2021/11/11 20:11
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");
        //判断是否有传token
        if (token == null || "".equals(token)) {
            log.info("login token is null");
            returnJson(response);
            return false;
        }

        //解析传入的token，获得后台user_id
        String userName = JWTUtils.getValue(token, BusinessConstant.LOGIN_USER_ID_KEY);
        if (userName == null) {
            log.info("login token 失效！");
            returnJson(response);
            return false;
        }

        UserDTO user = SessionLocal.getUser();
        if (ObjectUtils.isEmpty(user)) {
            UserDTO userDTO = new UserDTO();
            userDTO.setUserName(userName);
            userDTO.setToken(token);
            SessionLocal.setUser(userDTO);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        SessionLocal.remove();
    }

    private void returnJson(HttpServletResponse response) {
        returnJson(response, "用户令牌token无效，请重新登录");
    }

    private void returnJson(HttpServletResponse response, String errorDesc) {
        PrintWriter writer = null;
        response.setCharacterEncoding(CharEncoding.UTF_8);
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            ApiResult apiResult = new ApiResult();
            apiResult.setResultCode(401);
            apiResult.setErrMsg(errorDesc);
            writer.print(JSONObject.toJSON(apiResult));
        } catch (Exception e) {
            log.error("拦截器返回数据异常", e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

}
